/**
 * The MIT License (MIT)
 * Copyright (c) 2020 铭软科技(mingsoft.net)
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package net.mingsoft.cms.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.cms.biz.IContentShuffleBiz;
import net.mingsoft.cms.entity.ContentEntity;
import net.mingsoft.cms.entity.ContentShuffleTitleEntity;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 文章混淆管理控制层
 */
@Api(value = "文章混淆接口")
@Controller("cmsContentShuffleAction")
@RequestMapping("/${ms.manager.path}/cms/contentShuffle")
public class ContentShuffleAction extends BaseAction {
	
	Logger logger = LoggerFactory.getLogger(ContentShuffleAction.class);
	/**
	 * 注入文章业务层
	 */	
	@Autowired
	private IContentShuffleBiz contentBiz;

	/**
	 * 返回主界面index
	 */
//	@GetMapping("/index")
//	public String index(HttpServletResponse response,HttpServletRequest request){
//		return "/cms/contentshuffle/index";
//	}
	/**
	 * 返回主界面main
	 */
	 @GetMapping("/main") 
	 public String main(HttpServletResponse response,HttpServletRequest request){ 
		 return "/cms/contentshuffle/main"; 
	 }
	 
	 @Value("${ms.diy.artimg-dir}")
	 private String imgDir;
	/**
	 * 查询文章标题列表
	 * @param content 文章实体
	 */
	@ApiOperation(value = "查询文章列表接口")
	@ApiImplicitParams({
    	@ApiImplicitParam(name = "title", value = "文章标题", required =false,paramType="query"),
    })
	@RequestMapping("/list")
	@ResponseBody
	public ResultData list(@ModelAttribute @ApiIgnore ContentShuffleTitleEntity content, HttpServletResponse response, HttpServletRequest request, @ApiIgnore ModelMap model, BindingResult result) {
		BasicUtil.startPage();
		List contentList = contentBiz.query(content);
		ResultData res = ResultData.build().success(new EUListBean(contentList,(int) BasicUtil.endPage(contentList).getTotal()));
		res.putAll(contentBiz.queryCounts());
		//获取图片数
		File dir = new File(imgDir);
		int count = 0;
		if(dir.exists()&&dir.isDirectory()) {
			for(File subFile:dir.listFiles()) {
				if(subFile.isFile()) {
					count++;
				}
			}
		}
		logger.info("图片地址imgDir:{}",imgDir);
		res.put("imgCount", count);
		res.put("imgDir", imgDir);
		
		return res;
	}
	
	/**
	 * 返回编辑界面content_form
	 */
	@GetMapping("/form")
	public String form(@ModelAttribute ContentEntity content, HttpServletResponse response, HttpServletRequest request, ModelMap model){
		model.addAttribute("appId", BasicUtil.getApp().getAppId());
		return "/cms/contentshuffle/form";
	}
	/**
	 * 首段
	 * @param content
	 * @param response
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/formhead")
	public String formhead(@ModelAttribute ContentEntity content, HttpServletResponse response, HttpServletRequest request, ModelMap model){
		model.addAttribute("appId", BasicUtil.getApp().getAppId());
		return "/cms/contentshuffle/formhead";
	}
	
	/**
	 * 中段
	 * @param content
	 * @param response
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/formbody")
	public String formbody(@ModelAttribute ContentEntity content, HttpServletResponse response, HttpServletRequest request, ModelMap model){
		model.addAttribute("appId", BasicUtil.getApp().getAppId());
		return "/cms/contentshuffle/formbody";
	}
	/**
	 * 尾段
	 * @param content
	 * @param response
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/formfoot")
	public String formfoot(@ModelAttribute ContentEntity content, HttpServletResponse response, HttpServletRequest request, ModelMap model){
		model.addAttribute("appId", BasicUtil.getApp().getAppId());
		return "/cms/contentshuffle/formfoot";
	}
	
	@ApiOperation(value = "保存文章标题列表接口")
	 @ApiImplicitParams({
    	@ApiImplicitParam(name = "contentTitle", value = "文章标题", required =true,paramType="query"),
	})
	/**
	* 保存文章标题
	* @param content 文章实体
	*/
	@PostMapping("/save")
	@ResponseBody
	@LogAnn(title = "保存文章标题", businessType = BusinessTypeEnum.INSERT)
	@RequiresPermissions("cms:contentshuffle:save")
	public ResultData save(@RequestBody Map map, HttpServletResponse response, HttpServletRequest request) {
		 ArrayList<String> contentTitles = (ArrayList<String>) map.get("contentTitles");
		 String catId= (String) map.get("catId");
		contentBiz.save(contentTitles,catId);
		return ResultData.build().success();
	}
	
	/**
	 * @param contents 文章实体
	 */
	@ApiOperation(value = "批量删除文章标题列表接口")
	@PostMapping("/delete")
	@ResponseBody
	@LogAnn(title = "删除文章标题", businessType = BusinessTypeEnum.DELETE)
	@RequiresPermissions("cms:contentshuffle:del")
	public ResultData delete(@RequestBody List<String> ids, HttpServletResponse response, HttpServletRequest request) {
		contentBiz.removeByIdss(ids);
		return ResultData.build().success();
	}
	
	
	@PostMapping("/savehead")
	@ResponseBody
	@LogAnn(title = "保存文章首段", businessType = BusinessTypeEnum.INSERT)
	@RequiresPermissions("cms:contentshuffle:savehead")
	public ResultData savehead(@RequestBody Map map, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
		String contents = (String) map.get("contents");
		String catId = (String) map.get("catId");
		contents = contents.substring(0, contents.length()-1);
		contentBiz.savehead(URLDecoder.decode(contents,"utf-8"),catId);
		return ResultData.build().success();
	}
	@PostMapping("/savebody")
	@ResponseBody
	@LogAnn(title = "保存文章中段", businessType = BusinessTypeEnum.INSERT)
	@RequiresPermissions("cms:contentshuffle:savebody")
	public ResultData savebody(@RequestBody Map map, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
		String contents = (String) map.get("contents");
		String catId = (String) map.get("catId");
		contents = contents.substring(0, contents.length()-1);
		contentBiz.savebody(URLDecoder.decode(contents,"utf-8"),catId);
		return ResultData.build().success();
	}
	@PostMapping("/saveend")
	@ResponseBody
	@LogAnn(title = "保存文章尾段", businessType = BusinessTypeEnum.INSERT)
	@RequiresPermissions("cms:contentshuffle:saveend")
	public ResultData saveend( @RequestBody Map map, HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException {
		String contents = (String) map.get("contents");
		String catId = (String) map.get("catId");
		contents = contents.substring(0, contents.length()-1);
		contentBiz.saveend(URLDecoder.decode(contents,"utf-8"),catId);
		return ResultData.build().success();
	}
}
